﻿using System;
using Transformable_Engine_v2.Engine.Global;

namespace Transformable_Engine_v2.Engine.Animation.FrameAnimation
{
    public class FrameAnimation : BaseAnimation
    {
        public IFrameAnimatable AffectedObject { get; set; }
        public FrameAnimationDescription Animation { get; private set; }

        public delegate void OnChangeFrameHandler(int frameId);
        public event OnChangeFrameHandler OnChangeFrame;

        public FrameAnimation(FrameAnimationDescription animationDescription) 
            : base(animationDescription.Frames[0].Duration, true, 
                   animationDescription.Delay, animationDescription.AutoStart)
        {
            Animation = animationDescription;
        }

        public FrameAnimation(FrameAnimationDescription animationDescription, double delay) 
            : base(animationDescription.Frames[0].Duration, true, 
                   animationDescription.Delay + delay, animationDescription.AutoStart)
        {
            Animation = animationDescription;
        }

        protected override void DelayEnd()
        {
            AffectedObject.ClearOtherFrameAnimations(this);

            AffectedObject.SetFrame(Animation.CurrentFrame.Sprite);
            DurationTimer.Reset(Animation.CurrentFrame.Duration);

            if (OnChangeFrame != null)
                OnChangeFrame(Animation.CurrentFrame.Id);

            Animation.ChangeFrame();

            base.DelayEnd();
        }

        public override void Update(TimeSpan gameTime)
        {
        }

        protected override void DurationEnd()
        {
            if (OnChangeFrame != null)
                OnChangeFrame(Animation.CurrentFrame.Id);

            if(AffectedObject != null)
                AffectedObject.SetFrame(Animation.CurrentFrame.Sprite);

            if(Animation.IsFinished()) 
            {
                DurationTimer.Stop();
                Die();
            } 
            else
            {
                DurationTimer.Reset(Animation.CurrentFrame.Duration);
                Animation.ChangeFrame();
            }

            base.DurationEnd();
        }

        public override void Die()
        {
            AffectedObject = null;
            base.Die();
        }

    }
}